package com.abbas.smartCity.ui;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.text.Html;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.ScrollView;

import androidx.annotation.NonNull;
import androidx.lifecycle.LiveData;

import com.abbas.smartCity.App;
import com.abbas.smartCity.R;
import com.abbas.smartCity.adapter.BannerImageAdapter2;
import com.abbas.smartCity.adapter.ListCommAdapter;
import com.abbas.smartCity.base.BaseFragment;
import com.abbas.smartCity.bean.HomeBannerBean;
import com.abbas.smartCity.bean.HomeNewsBean;
import com.abbas.smartCity.bean.HomeNewsTypeBean;
import com.abbas.smartCity.bean.NetBean;
import com.abbas.smartCity.bean.ServerBean;
import com.abbas.smartCity.bean.ServerDTO;
import com.abbas.smartCity.retroft.ICallback;
import com.abbas.smartCity.retroft.ICallback2;
import com.bumptech.glide.Glide;
import com.google.android.material.tabs.TabLayout;
import com.youth.banner.Banner;
import com.youth.banner.indicator.CircleIndicator;
import com.youth.banner.transformer.AlphaPageTransformer;

import java.util.List;
import java.util.Objects;

import retrofit2.Call;

/**
 * 主页碎片
 */
public class HomeFragment extends BaseFragment {

    private EditText searchEt;//搜索框
    private Banner<HomeBannerBean.RowsBean, BannerImageAdapter2<HomeBannerBean.RowsBean>> banner;//轮播
    private GridView gv;//全部服务
    private TabLayout tab;//新闻类别
    private ListView lv;//新闻列表
    private ListCommAdapter<HomeNewsBean.RowsBean, ListCommAdapter.NewsHolder> adapter;//新闻列表适配器

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initView() {
        searchEt = (EditText) rootView.findViewById(R.id.search_et);
        banner = rootView.findViewById(R.id.banner);
        gv = (GridView) rootView.findViewById(R.id.gv);
        tab = (TabLayout) rootView.findViewById(R.id.tab);
        lv = (ListView) rootView.findViewById(R.id.lv);
    }

    @Override
    protected void initData() {
        //获取轮播数据
        api.getHomeBanner().enqueue(new ICallback<HomeBannerBean>() {
            @Override
            public void onSuccess(Call<HomeBannerBean> call, HomeBannerBean data) {
                //将数据类型转换为Object。反而更麻烦了
//                final List<Object> imList = data.getRows().stream()
//                        .map(HomeBannerBean.RowsBean::getAdvImg)
//                        .map(d -> (Object) d)
//                        .collect(Collectors.toList());
                banner.setAdapter(new BannerImageAdapter2<>(data.getRows()))
                        .setOnBannerListener((o, i) -> {//轮播点击事件
                            //跳转到新闻详情页面
                            final Intent intent = new Intent(requireContext(), DetailActivity.class);
                            final HomeBannerBean.RowsBean rowsBean = data.getRows().get(i);
                            intent.putExtra("id", rowsBean.getTargetId());
                            startActivity(intent);
                        })
                        .setIndicator(new CircleIndicator(Objects.requireNonNull(getContext())))
                        .setPageTransformer(new AlphaPageTransformer())
                        .start();
            }
        });

        //全部服务数据
        api.getServer().enqueue(new ICallback<ServerBean>() {
            @Override
            public void onSuccess(Call<ServerBean> call, ServerBean data) {
                //只取7个，构造一个 全部服务 并加入进去。共8个
                final List<ServerBean.RowsBean> rowsBeans = data.getRows().subList(0, 9);
                final ServerBean.RowsBean rowsBean = new ServerBean.RowsBean();
                rowsBean.setServiceName("更多服务");
                rowsBeans.add(rowsBean);

                gv.setAdapter(new ListCommAdapter<ServerBean.RowsBean, ListCommAdapter.ServerHolder>(
                        rowsBeans,
                        ListCommAdapter.ServerHolder.class,
                        R.layout.server_item
                ) {
                    @Override
                    protected void show(ServerBean.RowsBean data, View convertView, ServerHolder viewHolder, int position, Context context) {
                        //最后一项服务设置图片为更多服务
                        if (position == 9) {
                            Glide.with(context)
                                    .load(R.drawable.more_server)
                                    .into(viewHolder.im);
                        } else {
                            Glide.with(context)
                                    .load(App.getBaseUrl() + data.getImgUrl())
                                    .into(viewHolder.im);
                        }
                        viewHolder.tv.setText(data.getServiceName());
                    }
                });
            }
        });

        //新闻类型数据
        api.getNewsType().enqueue(new ICallback<HomeNewsTypeBean>() {
            @Override
            public void onSuccess(Call<HomeNewsTypeBean> call, HomeNewsTypeBean data) {
                final List<HomeNewsTypeBean.DataBean> rows = data.getData();
                //根据新闻类型数量添加tab
                rows.forEach(dataBean -> {
                    final TabLayout.Tab newTab = HomeFragment.this.tab.newTab();
                    newTab.setText(dataBean.getName());
                    newTab.setTag(dataBean.getId());
                    tab.addTab(newTab);
                });
            }
        });

        //默认获取第一种类型新闻，第一种新闻类型ID为 9
        getNews(9);
    }

    @Override
    protected void initEvent() {
        //新闻类型点击
        tab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                //加载对应类型新闻
                final Integer typeId = (Integer) tab.getTag();
                getNews(typeId);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        //新闻列表点击
        lv.setOnItemClickListener((adapterView, view, i, l) -> {
            //跳转值新闻详情页面
            final Intent intent = new Intent(requireContext(), DetailActivity.class);
            final HomeNewsBean.RowsBean item = adapter.getItem(i);
            intent.putExtra("id", item.getId());
            startActivity(intent);
        });

        //开始搜索
        searchEt.setOnEditorActionListener((textView, i, keyEvent) -> {
            if (EditorInfo.IME_ACTION_SEARCH == i) {
                // 跳转至搜索结果页面
                final Intent intent = new Intent(requireActivity(), SearchResultActivity.class);
                intent.putExtra("data", searchEt.getText().toString());
                searchEt.setText("");
                startActivity(intent);
            }
            return false;
        });

        //服务点击，第8条跳转值全部服务页面
        gv.setOnItemClickListener((adapterView, view, i, l) -> {
            if (i == 9) {
                HomeActivity.bnv.setSelectedItemId(R.id.all_server);
            }
        });
    }

    /**
     * 获取对应类型的新闻
     *
     * @param typeId 类型ID
     */
    private void getNews(Integer typeId) {
        api.getHomeNews(typeId, null).enqueue(new ICallback<HomeNewsBean>() {
            @Override
            public void onSuccess(Call<HomeNewsBean> call, HomeNewsBean data) {
                final List<HomeNewsBean.RowsBean> rows = data.getRows();
                if (adapter == null) {
                    adapter = new ListCommAdapter<HomeNewsBean.RowsBean, ListCommAdapter.NewsHolder>(
                            rows,
                            ListCommAdapter.NewsHolder.class,
                            R.layout.news_item
                    ) {
                        @SuppressLint("SetTextI18n")
                        @Override
                        protected void show(HomeNewsBean.RowsBean data, View convertView, NewsHolder viewHolder, int position, Context context) {
                            viewHolder.title.setText(data.getTitle());
                            Glide.with(context)
                                    .load(App.getBaseUrl() + data.getCover())
                                    .into(viewHolder.im);
                            viewHolder.sub.setText(Html.fromHtml(data.getContent()));
                            viewHolder.tag1.setText("评论总数：" + data.getCommentNum());
                            viewHolder.tag2.setText("发布时间：" + data.getPublishDate());
                        }
                    };
                    lv.setAdapter(adapter);
                } else {
                    adapter.resetData(rows);
                }
            }
        });
    }


}